<?php

namespace App\Http\Controllers\Admin;

use App\GameConfig;
use App\GamePrize;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PrizeController extends Controller
{

    //
    public function index(Request $request){
        return view('admin.prize.list');
    }
    public function ajax_list(Request $request){

        $model= GamePrize::query()
        ;

        if($request->searchKey){
            $model=$model->where('name','like', '%'.$request->searchKey.'%');
        }
        $model=$model->paginate($request->limit)
            ->toArray();
        return $this->page_json_render($model);
    }
    //创建
    public function create(Request $request){
        return view('admin.prize.edit_add');
    }
    //储存
    public function store(Request $request){
        $name=$request->name;
        $value=$request->value;
        $this->filter($request);
        $model=new GamePrize();
        $model->name=$request->name;
        $model->value=$request->value;
        $model->game_id=1;
        $model->save();
        return redirect()->route('admin.prize_index')->with(
            $this->success()
        );
    }
    //编辑
    public function edit(Request $request,$id){
        $model=GamePrize::findOrFail($id);
        return view('admin.prize.edit_add',compact('id','model'));
    }
    public function update(Request $request){
        $id=$request->id;
        $this->filter($request);
        $model=GamePrize::findOrFail($id);
        $model->name=$request->name;
        $model->value=$request->value;
        $model->game_id=1;
        $model->save();
        return redirect()->route('admin.prize_index')->with(
            $this->success()
        );
    }
    public function del(Request $request){
        $id=$request->id;
        $check=GameConfig::where('prize_id',$id)->first();
        if($check){
            return [
                'info'=>'fail',
                'msg'=>'奖品正在游戏中使用'
            ];
        }
        $model=GamePrize::findOrFail($id);

        $model->delete();
        return $this->del_success();
    }
    protected function filter($request){
        $this->validate($request,
            [
                'name'=>'required',
                'value'=>'required'
            ]);
    }
}
